package com.xu.cloud.common.advice;

import com.xu.cloud.common.constant.HttpConstant;
import com.xu.cloud.common.constant.OrderConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 请求属性设置响应结果后置通知处理器
 *
 * @author xuguan
 * @since 2025/1/7
 */
@Order(OrderConstant.RESULT_REQUEST_ATTRIBUTE_SETTING_ADVICE_ORDER)
@RestControllerAdvice
@Slf4j
@SuppressWarnings("NullableProblems")
public class ResponseRequestAttributeSettingAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return !Void.class.isAssignableFrom(returnType.getParameterType())
                && !void.class.isAssignableFrom(returnType.getParameterType());
    }

    @Nullable
    @Override
    public Object beforeBodyWrite(@Nullable Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (request instanceof ServletServerHttpRequest && Objects.nonNull(body)) {
            final HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
            servletRequest.setAttribute(HttpConstant.XU_CLOUD_RESPONSE_ATTRIBUTE_NAME, body);
        }
        return body;
    }
}
